﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VehicleScale.DataAccess;
using VehicleScale.Models;
using Janus.Windows.GridEX;
using System.Diagnostics;
using Janus.Windows.ButtonBar;
using VehicleScale.Reports;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
using CrystalDecisions.Shared;

namespace VehicleScale.Forms.Vehicles
{
    public partial class FrmVehicleScale : TemplateForm
    {

        #region Ctors

        /// <summary>
        /// Constructor for create new status
        /// </summary>
        public FrmVehicleScale()
            : base()
        {
            _vehicleScale = new VehicleScaleModel() { IsNew = true };

            InitializeComponent();
            Initialize();
            try
            {
                LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Mo Form Can xe moi");
            }
            catch
            {
            }
        }

        /// <summary>
        /// Constructor for create new status
        /// </summary>
        public FrmVehicleScale(VehicleScaleModel vehicleScale)
            : base()
        {
            VehicleScale = vehicleScale;
            _isList = true;
            VehicleScale.VehicleScaleDetails = VehicleScale.VehicleScaleDetails.OrderBy(x => x.ScaleTime2).ToList();
            InitializeComponent();
            Initialize();
            try
            {
                LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Dieu chinh Form Phieu Can xe, Ma phieu : " + VehicleScale.VehicleScaleID);
            }
            catch
            {
            }
        }

        #endregion

        #region Field Members
        private bool _isBinding = false;
        private IVehicleScaleDataAccess _dataAccess = new VehicleScaleDataAccess();
        private bool _isList = false; // Mo Form voi du lieu lay tu danh sach co san
       // private bool _isEdit = false; // Xem co chinh sua gi ko?
        private bool _isSelectedGrid = false;
        private decimal _firstweight = 0;
        private decimal _secondweight = 0;
        /// <summary>
        /// Button Bar Item of This Form
        /// </summary>
        private ButtonBarItem _buttonBarItem;

        #endregion

        #region Property Members

        #region Vehicle Scale Property
        private VehicleScaleModel _vehicleScale;
        /// <summary>
        /// Vehicle Scale Property
        /// </summary>
        public VehicleScaleModel VehicleScale
        {
            get { return _vehicleScale; }
            set
            {
                if (_vehicleScale != value)
                {
                    _vehicleScale = value;
                }
            }
        }
        #endregion

        #region Vehicle Scale Detail Property
        private VehicleScaleDetailModel _vehicleScaleDetail = new VehicleScaleDetailModel();
        /// <summary>
        /// Vehicle Scale Detail Property
        /// </summary>
        public VehicleScaleDetailModel VehicleScaleDetail
        {
            get
            {
                return _vehicleScaleDetail;
            }
            set
            {
                if (_vehicleScaleDetail != value)
                    _vehicleScaleDetail = value;
            }
        }
        #endregion

        #region This Key Property
        private string _thisKey = String.Empty;
        /// <summary>
        /// Customer key of this form.
        /// </summary>
        public string ThisKey
        {
            get { return _thisKey; }
            set
            {
                if (_thisKey != value)
                {
                    // Change key.
                    if (Common.SelectedCustomerIDs.Contains(_thisKey))
                        Common.SelectedCustomerIDs.Remove(_thisKey);
                    if (!Common.SelectedCustomerIDs.Contains(value) && !String.IsNullOrEmpty(value))
                        Common.SelectedCustomerIDs.Add(value);
                    _thisKey = value;
                }
            }
        }
        #endregion

        #endregion

        #region Methods

        #region Init control and process control
        /// <summary>
        /// Initialize method
        /// </summary>
        private void Initialize()
        {
            this.gridEX1.BuiltInTexts[Janus.Windows.GridEX.GridEXBuiltInText.GroupByBoxInfo] = "Chọn cột cần group.";

            #region Set value to some controls
            this.MaximizeBox = false;
            this.cboCustomerID.AutoComplete = false;

            if (_vehicleScale.IsNew)
            {
                // High light the active customer control
                _buttonBarItem = new ButtonBarItem();
                _buttonBarItem.Image = global::VehicleScale.Properties.Resources.customer;
                _buttonBarItem.Click += new ItemEventHandler(delegate
                {
                    this.Activate();
                });

                FrmMDI.Instance.btnBarCustomerList.Groups[0].Items.Add(_buttonBarItem);
                this.cboCustomerID.ValueChanged += new EventHandler(delegate { ActiveCustomer(); });
            }
            #endregion

            #region Set events to general controls
            this.cboCustomerID.TextChanged += new EventHandler(delegate { KeyDownFilterCustomer(); });
            this.cboCategoryID.ValueChanged += new EventHandler(delegate { FilterProduct(); });
            this.cboProductID.ValueChanged += new EventHandler(cboProductID_ValueChanged);
            this.ctrlVehicleID1.TextChanged += new EventHandler(ctrlVehicleID1_TextChanged);
            #endregion

            #region Set events to buttons
            this.btnSave.Click += new EventHandler(delegate
            {
                if (ClickButtonSave(false))
                {
                    MessageBox.Show("Phiếu cân đã được lưu!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                };
            });

            this.btnClose.Click += new EventHandler(delegate { this.Close(); });
            this.btnPrintAndSave.Click += new EventHandler(delegate { ClickButtonSave(true); });
            this.btnFirstWeight.Click += new EventHandler(delegate { ClickFirstWeight(); });
            this.btnSecondWeight.Click += new EventHandler(delegate { ClickSecondWeight(); });
            
            this.btnRefresh.Click += new EventHandler(delegate
            {
                this.cboCustomerID.DropDownList.Refetch();
                this.cboCategoryID.DropDownList.Refetch();
                this.cboProductID.DropDownList.Refetch();
            });
            // Process Details
            this.btnAddVehicle.Click += new EventHandler(delegate { ClickAddVehicle(); });

            #endregion

            #region Set events to grid
            this.gridEX1.ColumnButtonClick += new ColumnActionEventHandler(gridEX1_ColumnButtonClick);
            this.gridEX1.SelectionChanged += new EventHandler(delegate { SelectVehicleScaleDetail(); });
            this.chkManual.CheckedChanged += new EventHandler(delegate { chkManualCheckChanged(); });
            this.gridEX1.Click += new EventHandler(gridEX1_Click);
            #endregion

            // Set permission
            bool IsAdmin = (Common.UserLogin.GroupPermissionID == 1);
            this.numFirstWeight.ReadOnly = true;
            this.numSecondWeight.ReadOnly = true;
            this.chkManual.Visible = IsAdmin;
           
        }

       

        /// <summary>
        /// Reset detail controls
        /// </summary>
        private void ResetDetails()
        {
            this.ctrlVehicleID1.Text = String.Empty;
            this.numFirstWeight.Value = 0;
            this.numSecondWeight.Value = 0;
            this._firstweight = 0;
            this._secondweight = 0;
            _isSelectedGrid = false;
            this.cboCustomerID.Focus();
        }

        /// <summary>
        /// Active the selected customer.
        /// </summary>
        private void ActiveCustomer()
        {
            if (this.cboCustomerID.SelectedItem != null)
            {
                this.ThisKey = this.cboCustomerID.Value.ToString();
                this.cboCustomerID.DroppedDown = false;
            }
            else
            {
                this.ThisKey = String.Empty;
            }
            this.Text = String.Format("[{0}] / {1}", this.ThisKey, DateTime.Now.ToString());
            _buttonBarItem.Text = String.Format("[{0}]", this.ThisKey);
        }

        /// <summary>
        /// Init control values.
        /// </summary>
        private void InitControls()
        {
            this.btnFirstWeight.Enabled = false;
            this.cboCustomerID.SelectedIndex = -1;
            this.cboProductID.SelectedIndex = -1;
            this.ctrlVehicleID1.Text = String.Empty;
            this.numFirstWeight.Value = 0;
            this.numSecondWeight.Value = 0;

            this.cboCustomerID.Focus();
        }

        /// <summary>
        /// Validates controls.
        /// </summary>
        private void ValidatingControls()
        {
            string errorMessage;
            this.cboCustomerID.Validating += new CancelEventHandler(delegate
            {
                errorMessage = (this.cboCustomerID.Value == null) ?
                    ErrorException.Error("Khách hàng", errType.mustbechosen) : String.Empty;
                errorProvider.SetError(this.cboCustomerID, errorMessage);
            });

            this.cboProductID.Validating += new CancelEventHandler(delegate
            {
                errorMessage = (this.cboProductID.Value == null) ?
                    ErrorException.Error("Sản phẩm", errType.mustbechosen) : String.Empty;
                errorProvider.SetError(this.cboProductID, errorMessage);
            });

            this.ctrlVehicleID1.Validating += new CancelEventHandler(delegate
            {
                errorMessage = String.IsNullOrEmpty(this.ctrlVehicleID1.Text) ?
                    ErrorException.Error("Số xe", errType.required) : String.Empty;
                errorProvider.SetError(this.ctrlVehicleID1, errorMessage);
            });

            this.numFirstWeight.Validating += new CancelEventHandler(delegate
            {
                if ((decimal)this.numFirstWeight.Value <= 0)
                {
                    errorProvider.SetError(this.numFirstWeight, "Trọng lượng của mỗi lần cân phải lớn hơn 0.");
                    this.btnFirstWeight.Enabled = false;
                }
                else
                {
                    errorProvider.SetError(this.numFirstWeight, String.Empty);
                    if (this.ctrlVehicleID1.TextLength > 0)
                    {
                        this.btnFirstWeight.Enabled = true;
                        this.btnFirstWeight.Focus();
                    }
                }
            });

            this.numSecondWeight.Validating += new CancelEventHandler(delegate
            {
                if ((decimal)this.numSecondWeight.Value <= 0)
                {
                    errorProvider.SetError(this.numSecondWeight, "Trọng lượng của mỗi lần cân phải lớn hơn 0.");
                    this.btnSecondWeight.Enabled = false;
                }
                else
                {
                    errorProvider.SetError(this.numSecondWeight, String.Empty);
                    if (this.ctrlVehicleID1.TextLength > 0 && (decimal)this.numFirstWeight.Value > 0)
                    {
                        this.btnSecondWeight.Enabled = true;
                        this.btnSecondWeight.Focus();
                    }
                }
            });
        }

        #endregion

        #region Binding Methods
        /// <summary>
        /// Reset binding control method.
        /// </summary>
        private void ResetBindingControls()
        {
            this.cboCustomerID.DataBindings.Clear();
            this.cboProductID.DataBindings.Clear();
            this.edtVehicleScaleID.DataBindings.Clear();

            this.gridEX1.DataBindings.Clear();

            ResetDetails();

            this._isBinding = false;
        }

        /// <summary>
        /// Binding control method.
        /// </summary>
        private void BindingControls()
        {
            if (!_isBinding)
            {
                this.cboCustomerID.DataBindings.Add("Value", VehicleScale, "CustomerID");
                this.cboProductID.DataBindings.Add("Value", VehicleScale, "ProductID");
                this.edtVehicleScaleID.DataBindings.Add("Text", VehicleScale, "ShortID");

                this.gridEX1.DataBindings.Add("DataSource", VehicleScale, "VehicleScaleDetails");

                _isBinding = true;
            }
        }
        #endregion

        #region Load data and device
        /// <summary>
        /// Load customer list to combo
        /// </summary>
        private void LoadCustomersToCombo()
        {
            this.cboCustomerID.DataSource = Common.Customers;
            this.cboCustomerID.ValueMember = "CustomerID";
            this.cboCustomerID.DisplayMember = "CustomerName";
        }

        /// <summary>
        /// Load category list to combo
        /// </summary>
        private void LoadCategoriesToCombo()
        {
            this.cboCategoryID.DataSource = Common.Categories;
            this.cboCategoryID.ValueMember = "CategoryID";
            this.cboCategoryID.DisplayMember = "CategoryName";
        }

        /// <summary>
        /// Load product list to combo
        /// </summary>
        private void LoadProductsToCombo()
        {
            this.cboProductID.DataSource = Common.Products;
            this.cboProductID.ValueMember = "ProductID";
            this.cboProductID.DisplayMember = "ProductName";
            this.cboProductID.DropDownList.Columns.Add("CategoryID", Janus.Windows.GridEX.ColumnType.Text, EditType.NoEdit).Visible = false;
        }

        /// <summary>
        /// Load serial port method.
        /// </summary>
        private void OpenSerialPort()
        {
            try
            {
                if (!Common.SerialPort.IsOpen) Common.SerialPort.Open();

                Common.SerialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort_DataReceived);
            }
            catch (Exception ex)
            {
                if (_vehicleScale != null && _vehicleScale.IsNew)
                {
                    Library.Tools.MsgBox.Show("Lỗi MỞ PORT! Error details: " + ex.Message +
                        String.Format("Port: {0}, Parity: {1}, StopBits: {2}, BaudRate: {3}, DataBits: {4}",
                        Common.SerialPort.PortName,
                        Common.SerialPort.Parity,
                        Common.SerialPort.StopBits,
                        Common.SerialPort.BaudRate,
                        Common.SerialPort.DataBits
                        ));
                }
                else
                {
                    Debug.WriteLine("Lỗi MỞ PORT! Error details: " + ex.Message +
                        String.Format("Port: {0}, Parity: {1}, StopBits: {2}, BaudRate: {3}, DataBits: {4}",
                        Common.SerialPort.PortName,
                        Common.SerialPort.Parity,
                        Common.SerialPort.StopBits,
                        Common.SerialPort.BaudRate,
                        Common.SerialPort.DataBits
                        ));
                }
            }
        }

        /// <summary>
        /// Load serial port method.
        /// </summary>
        private void FreeEventSerialPort()
        {
            try
            {
                Common.SerialPort.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort_DataReceived);
            }
            catch (Exception ex)
            {
                Library.Tools.MsgBox.Show("Lỗi đóng sự kiện lấy số cân: " + ex.Message +
                    String.Format("Port: {0}, Parity: {1}, StopBits: {2}, BaudRate: {3}, DataBits: {4}",
                    Common.SerialPort.PortName,
                    Common.SerialPort.Parity,
                    Common.SerialPort.StopBits,
                    Common.SerialPort.BaudRate,
                    Common.SerialPort.DataBits
                    ));
            }
        }
        #endregion

        #region Filter Methods
        /// <summary>
        /// Filter customer list in the combo box.
        /// </summary>
        private void FilterCustomerCombo()
        {
            GridEXFilterCondition condition = new GridEXFilterCondition();
            condition.Column = this.cboCustomerID.DropDownList.RootTable.Columns["CustomerID"];
            condition.ConditionOperator = ConditionOperator.NotIn;
            condition.Value1 = Common.SelectedCustomerIDs;

            GridEXFilterCondition condition1 = new GridEXFilterCondition();
            condition1.Column = this.cboCustomerID.DropDownList.RootTable.Columns["CustomerID"];
            condition1.ConditionOperator = ConditionOperator.Equal;
            condition1.Value1 = this.ThisKey;

            condition.AddCondition(LogicalOperator.Or, condition1);

            this.cboCustomerID.DropDownList.RootTable.FilterCondition = condition;
        }

        /// <summary>
        /// Filter customer list in the combo box with the enclosed parameters.
        /// </summary>
        /// <param name="condition2"></param>
        private void FilterCustomerCombo(GridEXFilterCondition condition2)
        {
            GridEXFilterCondition condition = new GridEXFilterCondition();
            condition.Column = this.cboCustomerID.DropDownList.RootTable.Columns["CustomerID"];
            condition.ConditionOperator = ConditionOperator.NotIn;
            condition.Value1 = Common.SelectedCustomerIDs;

            GridEXFilterCondition condition1 = new GridEXFilterCondition();
            condition1.Column = this.cboCustomerID.DropDownList.RootTable.Columns["CustomerID"];
            condition1.ConditionOperator = ConditionOperator.Equal;
            condition1.Value1 = this.ThisKey;

            condition.AddCondition(LogicalOperator.Or, condition1);
            condition.AddCondition(LogicalOperator.And, condition2);

            this.cboCustomerID.DropDownList.RootTable.FilterCondition = condition;
        }

        /// <summary>
        /// Filter the customer list.
        /// </summary>
        private void KeyDownFilterCustomer()
        {

            this.cboCustomerID.DroppedDown = false;
            GridEXFilterCondition condition = new GridEXFilterCondition();
            condition.Column = this.cboCustomerID.DropDownList.RootTable.Columns["CustomerName"];
            condition.ConditionOperator = ConditionOperator.Contains;
            condition.Value1 = cboCustomerID.Text;

            FilterCustomerCombo(condition);
            try
            {
                LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Chon khach hang: " + this.cboCustomerID.Value.ToString());
            }
            catch
            {
            }
                this.cboCustomerID.DroppedDown = true;
        }

        /// <summary>
        /// Filter the products list.
        /// </summary>
        private void FilterProduct()
        {
            if (this.cboProductID.DropDownList.CurrentRow != null
                && this.cboProductID.DropDownList.CurrentRow.Cells["CategoryID"].Value != cboCategoryID.Value)
            {
                this.cboProductID.SelectedIndex = -1;
            }

            GridEXFilterCondition condition = new GridEXFilterCondition();
            condition.Column = this.cboProductID.DropDownList.RootTable.Columns["CategoryID"];
            condition.ConditionOperator = ConditionOperator.Equal;
            condition.Value1 = cboCategoryID.Value;
            try
            {
                LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Chon loai san pham: " + this.cboCategoryID.Value.ToString());
            }
            catch
            {
            }
            //LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Chon san pham: " + this.cboProductID.SelectedText);
            this.cboProductID.DropDownList.RootTable.FilterCondition = condition;

        }

        void cboProductID_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Chon san pham: " + this.cboProductID.Value.ToString());
            }
            catch
            {
            }
        }
        #endregion

        #endregion

        #region Serial Port Events

        string _data = String.Empty;

        /// <summary>
        /// Event Receive Data From Scale Device.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                string vehicleID = this.ctrlVehicleID1.Text.Trim();
                if (vehicleID != String.Empty && !this.chkManual.Checked)
                {
                    string dataReceived = Common.SerialPort.ReadExisting();

                    // Data:
                    // 4B 47 4D 0D 0A 02 20 20 20 20 33 33 38 30 4B 47
                    _data = String.Concat(_data, dataReceived);

                    // Get String with Start Index
                    int startIndex = _data.IndexOf(Convert.ToChar(2));    // index = 5;
                    if (startIndex >= 0)
                    {
                        _data = _data.Substring(startIndex + 1);
                    }


                    // Get String with End Index and Print It.
                    int endIndex = _data.IndexOf(Convert.ToChar(0x4B));

                    if (endIndex >= 0)
                    {
                        _data = _data.Substring(0, endIndex);
                        _data = _data.Trim();
                        Console.WriteLine(_data);

                        // Print it
                        ParingData(_data);
                        _data = String.Empty;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Receive data failed. Error details: " + ex.Message);
            }
        }

        #region Receiving Data From COM Port
        private void ParingData(string data)
        {
            if (!VehicleScaleDetail.HasFirstWeight)
            {
                //MessageBox.Show("Cân 1: " + data);
                this.numFirstWeight.Invoke(new EventHandler(delegate { this.numFirstWeight.Value = Int32.Parse(data); }));
            }
            else if (!VehicleScaleDetail.HasSecondWeight)
            {
                //MessageBox.Show("Cân 2" + data);
                this.numSecondWeight.Invoke(new EventHandler(delegate { this.numSecondWeight.Value = Int32.Parse(data); }));
            }
        }
        #endregion

        #endregion

        #region Events

        #region Form Events
        protected override void OnLoad(EventArgs e)
        {
            LoadCustomersToCombo();
            LoadCategoriesToCombo();
            LoadProductsToCombo();
            BindingControls();
            ValidatingControls();


            if (_vehicleScale.IsNew)
            {
                //ClickAddVehicle();
                InitControls();
            }
            else
            {
                _vehicleScale.IsEdit = false;
                this.cboCustomerID.Value = _vehicleScale.CustomerID;
                this.cboCustomerID.DroppedDown = false;
                this.cboCategoryID.Value = _vehicleScale.Product.CategoryID;
                this.cboProductID.Value = _vehicleScale.ProductID;
                switch (_vehicleScale.ImExType)
                {
                    case 1:
                        this.rdoImportProducts.Checked = true;
                        break;
                    case 2:
                        this.rdoExportProducts.Checked = true;
                        break;
                }

                // Set permission
                //bool IsAdmin = (Common.UserLogin.GroupPermissionID == 1);
                //this.btnSave.Visible = IsAdmin;
                //this.btnPrintAndSave.Visible = IsAdmin;
            }
            base.OnLoad(e);
        }

        /// <summary>
        /// Event on activated
        /// </summary>
        /// <param name="e"></param>
        protected override void OnActivated(EventArgs e)
        {

            if (_vehicleScale.IsNew)
            {
                this.Text = String.Format("Khách hàng [{0}] / {1}", this.ThisKey, DateTime.Now.ToString());
                _buttonBarItem.Text = String.Format("Khách hàng [{0}]", this.ThisKey);
                _buttonBarItem.ButtonBar.SelectedItem = _buttonBarItem;

                cboCustomerID.Refresh();
                cboCategoryID.Refresh();
                cboProductID.Refresh();

                FilterCustomerCombo();
            }
            OpenSerialPort();

            base.OnActivated(e);
        }

        protected override void OnDeactivate(EventArgs e)
        {
            FreeEventSerialPort();

            base.OnDeactivate(e);
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.F5)
            {
                ClickResetFirstWeight();
            }
            else if (e.Control && e.KeyCode == Keys.F7)
            {
                ClickResetSecondWeight();
            }
            base.OnKeyDown(e);
        }
        #endregion

        #region General Controls Events. Such as: TextBox, ComboBox, Control, etc.
        void ctrlVehicleID1_TextChanged(object sender, EventArgs e)
        {
            if (VehicleScaleDetail != null)
            {
                VehicleScaleDetail.VehicleID = this.ctrlVehicleID1.Text;
                this.gridEX1.UpdateData();
                this.gridEX1.Refresh();
            }
        }
        #endregion

        #region Data Grid Events
        /// <summary>
        /// Click on grid to change Vehicle IDm First Weight and Last Weight
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void gridEX1_Click(object sender, EventArgs e)
        {
            if (this.ctrlVehicleID1.Enabled &&
                this.gridEX1.CurrentRow != null &&
                this.gridEX1.CurrentRow.RowType == RowType.Record)
            {
                _isSelectedGrid = true;
                SelectVehicleScaleDetail();
            }

            if (this.gridEX1.CurrentRow != null &&
                this.gridEX1.CurrentColumn != null &&
                this.gridEX1.CurrentRow.RowType == RowType.TotalRow &&
                this.gridEX1.CurrentColumn.Key == "TotalWeight" &&
                this.gridEX1.CurrentRow.Cells["TotalWeight"].Text != "0")
            {
                FrmVehicleScaleSplit form = new FrmVehicleScaleSplit(VehicleScale.VehicleScaleSplits);
                form.TotalWeight = Decimal.Parse(this.gridEX1.GetTotalRow().Cells["TotalWeight"].Text);
                DialogResult result = form.ShowDialog();
                if (result == DialogResult.OK)
                {
                    VehicleScale.VehicleScaleSplits = form.SplitCollection;
                }
            }

        }

        /// <summary>
        /// Button delete one vehicle on grid.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void gridEX1_ColumnButtonClick(object sender, ColumnActionEventArgs e)
        {
            if (e.Column.Key == "ButtonDelete")
            {
                VehicleScaleDetailModel model = this.gridEX1.CurrentRow.DataRow as VehicleScaleDetailModel;
                if (model == null) return;
                if (Common.UserLogin.GroupPermissionID != 1 &&
                    new FrmAuthorize().ShowDialog() != DialogResult.OK) return;


                if (VehicleScale.VehicleScaleDetails.Count == 0)
                {
                    switch (VehicleScale.ImExType)
                    {
                        case 0:
                            this.rdoImportProducts.Checked = true;
                            break;
                        case 1:
                            this.rdoExportProducts.Checked = true;
                            break;
                    }
                }
                this.ctrlVehicleID1.Focus();

                // Recount total
                VehicleScale.TotalFirstWeight = Convert.ToDecimal(gridEX1.GetTotalRow().Cells["FirstWeight"].Value);
                VehicleScale.TotalSecondWeight = Convert.ToDecimal(gridEX1.GetTotalRow().Cells["SecondWeight"].Value);

                string detailerror;
                if (RemoveVehicleItem(out detailerror))
                    this.gridEX1.CurrentRow.Delete();
                else
                {
                    Library.Tools.MsgBox.Show(String.Format(Messages.DeleteFailedMessage + Environment.NewLine + "Chi tiết lỗi: " + detailerror, "phiếu cân"),
                                    "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        #endregion

        #endregion

        #region Action Members

        #region Select vehicle scale detail
        /// <summary>
        /// Select a vehicle scale detail.
        /// </summary>
        private void SelectVehicleScaleDetail()
        {
            if (gridEX1.CurrentRow != null && gridEX1.CurrentRow.RowType == RowType.Record)
            {
                VehicleScaleDetail = gridEX1.CurrentRow.DataRow as VehicleScaleDetailModel;

                if (VehicleScaleDetail != null && VehicleScaleDetail.VehicleID != null)
                {
                    _firstweight = VehicleScaleDetail.FirstWeight;
                    _secondweight = VehicleScaleDetail.SecondWeight;
                    
                    this.ctrlVehicleID1.Text = VehicleScaleDetail.VehicleID;

                    this.numFirstWeight.Value = VehicleScaleDetail.FirstWeight;
                    this.numSecondWeight.Value = VehicleScaleDetail.SecondWeight;
                    if (VehicleScaleDetail.HasFirstWeight)
                    {
                        //this.numFirstWeight.Enabled = false;
                        this.btnFirstWeight.Enabled = false;
                    }

                    if (VehicleScaleDetail.HasSecondWeight)
                    {
                        //this.numSecondWeight.Enabled = false;
                        this.btnSecondWeight.Enabled = false;
                    }
                    try
                    {
                        LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Chon phieu can tren Grid, SL 1: " + VehicleScaleDetail.FirstWeight + " , SL 2 : " + VehicleScaleDetail.SecondWeight);
                    }
                    catch
                    {
                    }
                }
                else
                {
                    ResetDetails();
                }
            }
        }
        #endregion

        #region Click first weight button
        private void ClickFirstWeight()
        {

            if (String.IsNullOrEmpty(this.ctrlVehicleID1.Text))
            {
                //Library.Tools.MsgBox.Show("Bạn phải nhập số xe cân lần đầu!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                decimal firstWeight = (decimal)this.numFirstWeight.Value;

                if (firstWeight <= 0) return;

                VehicleScaleDetail.FirstWeight = firstWeight;
                VehicleScaleDetail.ScaleTime1 = DateTime.Now;
                

                // Refresh data
                this.gridEX1.Refresh();

                VehicleScale.TotalFirstWeight = Convert.ToDecimal(gridEX1.GetTotalRow().Cells["FirstWeight"].Value);
                try
                {
                    LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Click Can lan 1" + ", Ma phieu : " + VehicleScale.VehicleScaleID);
                    //this.btnAddVehicle.Enabled = true;
                }
                catch
                {
                }
                this.numSecondWeight.Focus();
            }

        }
        #endregion

        #region Click second weight button
        private void ClickSecondWeight()
        {
            decimal firstWeight = (decimal)this.numFirstWeight.Value;
            decimal secondWeight = (decimal)this.numSecondWeight.Value;

            if (firstWeight <= 0 || secondWeight <= 0) return;

            string vehicleID = this.ctrlVehicleID1.Text;

            // Just add a new record 
            if (VehicleScale.VehicleScaleDetails.Count == 1)
            {
                if (firstWeight > secondWeight)
                {
                    VehicleScale.ImExType = 1;
                    this.rdoImportProducts.Checked = true;
                }
                else
                {
                    VehicleScale.ImExType = 2;
                    this.rdoExportProducts.Checked = true;
                }
            }
            else
            {
                // Export scaling
                if (firstWeight > secondWeight && VehicleScale.ImExType == 2)
                {
                    Library.Tools.MsgBox.Show("Bạn đang XUẤT HÀNG. Không được NHẬP hàng!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.numSecondWeight.Focus();
                    return;
                }

                // Import scaling
                if (firstWeight < secondWeight && VehicleScale.ImExType == 1)
                {
                    Library.Tools.MsgBox.Show("Bạn đang NHẬP HÀNG. Không được XUẤT hàng!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.numSecondWeight.Focus();
                    return;
                }
            }


            VehicleScaleDetail.SecondWeight = secondWeight;
            VehicleScaleDetail.ScaleTime2 = DateTime.Now;


            // Refresh data
            this.gridEX1.Refresh();

            VehicleScale.TotalSecondWeight = Convert.ToDecimal(gridEX1.GetTotalRow().Cells["SecondWeight"].Value);

            if (gridEX1.RowCount == 15)
            {
                if (ValidToSave())
                {
                    string detailerror = string.Empty;
                    if (!SaveVehicleItem(out detailerror))
                    {
                        Library.Tools.MsgBox.Show(String.Format(Messages.ModifyFailedMessage + Environment.NewLine + "Chi tiết lỗi: " + detailerror, "phiếu cân"),
                                "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    if (MessageBox.Show("Đã cân đủ 15 phiếu cân. Bạn có muốn in phiếu cân?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        PrintReport();
                    }
                    this.Close();
                }
            }
            else
            {
                if (ValidToSave())
                {
                    if (gridEX1.RowCount == 1 && _vehicleScale.IsNew)
                    {
                        // Creating new ticket. Add new ticket with one details
                       
                     
                        VehicleScaleDetail.CreatedDate = DateTime.Now;
                        string detailerror = string.Empty;
                        if (!NewTicket(out detailerror))
                        {
                            Library.Tools.MsgBox.Show(String.Format(Messages.NewFailedMessage + Environment.NewLine + "Chi tiết lỗi: " + detailerror, "phiếu cân"),
                                    "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        string detailerror = string.Empty;
                        if (!SaveVehicleItem(out detailerror))
                        {
                            Library.Tools.MsgBox.Show(String.Format(Messages.ModifyFailedMessage + Environment.NewLine + "Chi tiết lỗi: " + detailerror, "phiếu cân"),
                                    "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            try
            {
                LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Click Can lan 2, Ma Phieu : " + VehicleScale.VehicleScaleID);
            }
            catch
            {
            }
            this.chkManual.Checked = false;
            this.ctrlVehicleID1.Focus();
        }
        #endregion

        #region Click save button

        private void chkManualCheckChanged()
        {
            string pass = String.Empty;
            if (this.chkManual.Checked)
            {
                if (ClassInput.InputBox("Chú ý", "Bạn phải nhập Password để nhập tay số cân", ref pass) == DialogResult.OK)
                {
                    if (pass.ToUpper() == Common.PassToScale)
                    {
                        this.numFirstWeight.ReadOnly = false;
                        this.numSecondWeight.ReadOnly = false;
                        this.numFirstWeight.Focus();
                    }
                    else
                    {
                        Library.Tools.MsgBox.Show("Password không đúng", "Thông báo");
                        this.chkManual.Checked = false;
                    }
                    try
                    {
                        LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Click Can bang tay");
                    }
                    catch
                    {
                    }
                }
                else
                    this.chkManual.Checked = false;
                
            }
            else
            {
                this.numFirstWeight.ReadOnly = true;
                this.numSecondWeight.ReadOnly = true;
                
            }
        }

        /// <summary>
        /// Click button save
        /// </summary>
        private bool ClickButtonSave(bool HasPrint)
        {
            bool result = false;

            try
            {
                //if (_isList)
                //{
                //    if (HasPrint)
                //    {
                //        PrintReport();
                //    }
                  
                //}
                //else
                //{
                    if (ValidToSave())
                    {
                        string detailerror = string.Empty;

                        if (gridEX1.RowCount == 1 && _vehicleScale.IsNew)
                        {
                            // Creating new ticket. Add new ticket with one details
                            if (!NewTicket(out detailerror))
                            {
                                Library.Tools.MsgBox.Show(String.Format(Messages.NewFailedMessage + Environment.NewLine + "Chi tiết lỗi: " + detailerror, "phiếu cân"),
                                        "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                if (HasPrint)
                                {                                   
                                    PrintReport();
                                }
                            }
                        }
                        else
                        {
                            if (!SaveVehicleItem(out detailerror))
                            {
                                Library.Tools.MsgBox.Show(String.Format(Messages.ModifyFailedMessage + Environment.NewLine + "Chi tiết lỗi: " + detailerror, "phiếu cân"),
                                        "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                if (HasPrint)
                                {
                                    
                                    PrintReport();
                                }
                            }
                        }
                    //}


                    //    }
                    //    else
                    //    {
                    //        if (_vehicleScale.IsNew)
                    //            Library.Tools.MsgBox.Show(String.Format(Messages.NewFailedMessage + Environment.NewLine + "Chi tiết lỗi: " + detailerror, "phiếu cân"),
                    //                "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //        else
                    //            Library.Tools.MsgBox.Show(String.Format(Messages.ModifyFailedMessage + Environment.NewLine + "Chi tiết lỗi: " + detailerror, "phiếu cân"),
                    //                "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //    }
                    //}
                }
            }
            catch(Exception ex)
            {
                Library.Tools.MsgBox.Show("Lỗi mở Report : " + ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
            return result;
        }

        //private bool Save(ref bool isNew, out string detailerror)
        //{
        //    detailerror = String.Empty;
        //    bool result = false;

        //    try
        //    {
        //        _vehicleScale.CustomerID = this.cboCustomerID.Value.ToString();
        //        _vehicleScale.ProductID = this.cboProductID.Value.ToString();
        //        _vehicleScale.EmployeeID = Common.UserLogin.EmployeeID;
        //        _vehicleScale.ScaleDate = DateTime.Today;
        //        _vehicleScale.ModifiedByID = Common.UserLogin.EmployeeID;
        //        _vehicleScale.ModifiedDate = DateTime.Now;
        //        _vehicleScale.TotalFirstWeight = (decimal)this.gridEX1.GetTotalRow().Cells["FirstWeight"].Value;
        //        _vehicleScale.TotalSecondWeight = (decimal)this.gridEX1.GetTotalRow().Cells["SecondWeight"].Value;

        //        if (_vehicleScale.IsNew)
        //        {
        //            _vehicleScale.CreatedByID = Common.UserLogin.EmployeeID;
        //            _vehicleScale.CreationDate = DateTime.Now;
        //            result = _dataAccess.Add(_vehicleScale, out detailerror);
        //            isNew = true;
        //        }
        //        else if (_vehicleScale.IsEdit)
        //        {
        //            result = _dataAccess.Edit(_vehicleScale, out detailerror);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Debug.WriteLine(ex.Message);
        //    }

        //    return result;
        //}

        private bool ValidToSave()
        {
            bool validInput = true;

            foreach (Control ctrl in this.uiGroupBox2.Controls)
            {
                if (errorProvider.GetError(ctrl) != String.Empty)
                {
                    validInput = false;
                    break;
                }
            }

            if (validInput)
            {
                if (VehicleScale.VehicleScaleDetails != null && VehicleScale.VehicleScaleDetails.Count == 0)
                {
                    Library.Tools.MsgBox.Show("Phiếu cân phải cân ít nhất 1 xe.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    validInput = false;
                }
                else if (VehicleScale.VehicleScaleDetails != null && VehicleScale.VehicleScaleDetails.Count(d => d.FirstWeight == 0 || d.SecondWeight == 0) > 0)
                {
                    Library.Tools.MsgBox.Show("Trọng lượng 2 lần cân phải lớn hơn 0.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    validInput = false;
                }
            }

            if (!validInput)
            {
                Library.Tools.MsgBox.Show(Messages.ValidateInfoMessage, Messages.NoticeTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                this.errorProvider.Clear();
            }

            return validInput;
        }
        #endregion

        private crScaleTicket BuildReport()
        {
            DataTable dataTable;
            DataSet ds = new DataSet();
            DataSet ds1 = new DataSet();

            // Master Report
            dataTable = CollectionExtensions<VehicleScaleModel>.ConvertToDataTable(new List<VehicleScaleModel>() { VehicleScale }, "VehicleScale");
            ds.Tables.Add(dataTable);

            dataTable = CollectionExtensions<CustomerModel>.ConvertToDataTable(new List<CustomerModel>() { this.cboCustomerID.SelectedItem as CustomerModel }, "Customer");
            ds.Tables.Add(dataTable);

            dataTable = CollectionExtensions<ProductModel>.ConvertToDataTable(new List<ProductModel>() { this.cboProductID.SelectedItem as ProductModel }, "Product");
            ds.Tables.Add(dataTable);

            IList<VehicleScaleDetailModel> detailcollection = new List<VehicleScaleDetailModel>();
            int length = VehicleScale.VehicleScaleDetails.Count;
            VehicleScaleDetailModel model = new VehicleScaleDetailModel();
            for (int i = 0; i < length; i += 3)
            {
                model = VehicleScale.VehicleScaleDetails.ElementAt(i);
                if (i + 1 < length)
                {
                    model.FirstWeight2 = VehicleScale.VehicleScaleDetails[i + 1].FirstWeight;
                    model.SecondWeight2 = VehicleScale.VehicleScaleDetails[i + 1].SecondWeight;
                    model.NumberEdited2 = VehicleScale.VehicleScaleDetails[i + 1].NumberEdited;
                }
                if (i + 2 < length)
                {
                    model.FirstWeight3 = VehicleScale.VehicleScaleDetails[i + 2].FirstWeight;
                    model.SecondWeight3 = VehicleScale.VehicleScaleDetails[i + 2].SecondWeight;
                    model.NumberEdited3 = VehicleScale.VehicleScaleDetails[i + 2].NumberEdited;
                }
                detailcollection.Add(model);
            }
            //var detail = VehicleScale.VehicleScaleDetails.Take(5) as IEnumerable<VehicleScaleDetailModel>;
            //var detail2 = VehicleScale.VehicleScaleDetails.Skip(5).Take(5);
            //int i = 0;
            //VehicleScaleDetailModel model;
            //foreach (var item in detail2)
            //{
            //    model = detail.ElementAt(i);
            //    model.FirstWeight2 = item.FirstWeight;
            //    model.SecondWeight2 = item.SecondWeight;
            //    i++;
            //}
            //var detail3 = VehicleScale.VehicleScaleDetails.Skip(10).Take(5);
            //i = 0;
            //foreach (var item in detail3)
            //{
            //    model = detail.ElementAt(i);
            //    model.FirstWeight3 = item.FirstWeight;
            //    model.SecondWeight3 = item.SecondWeight;
            //    i++;
            //}

            dataTable = CollectionExtensions<VehicleScaleDetailModel>.ConvertToDataTable(detailcollection, "VehicleScaleDetail");
            ds.Tables.Add(dataTable);

            ds.Relations.Add("FK_VehicleScale_Customer", ds.Tables["Customer"].Columns["CustomerID"], ds.Tables["VehicleScale"].Columns["CustomerID"]);
            ds.Relations.Add("FK_VehicleScale_Product", ds.Tables["Product"].Columns["ProductID"], ds.Tables["VehicleScale"].Columns["ProductID"]);
            ds.Relations.Add("FK_VehicleScaleDetail_VehicleScale", ds.Tables["VehicleScale"].Columns["VehicleScaleID"], ds.Tables["VehicleScaleDetail"].Columns["VehicleScaleID"]);
            /* *************************** */

            // Sub Report
            dataTable = CollectionExtensions<VehicleScaleSplitModel>.ConvertToDataTable(VehicleScale.VehicleScaleSplits, "VehicleScaleSplit");
            ds1.Tables.Add(dataTable);

            dataTable = CollectionExtensions<ProductModel>.ConvertToDataTable(Common.Products, "Product1");
            ds1.Tables.Add(dataTable);

            ds1.Relations.Add("Product1_VehicleScaleSplit", ds1.Tables["Product1"].Columns["ProductID"], ds1.Tables["VehicleScaleSplit"].Columns["ProductID"]);
            /* ***************************************** */

            crScaleTicket report = new crScaleTicket();
            report.SetDataSource(ds);
            report.Subreports["crSplitReport.rpt"].SetDataSource(ds1);
            if (_vehicleScale.VehicleScaleSplits.Count == 0)
            {
                report.ReportFooterSection2.SectionFormat.EnableSuppress = true;
            }
            report.SetParameterValue("CompanyName", Common.CompanyInfo.CompanyName);
            report.SetParameterValue("CompanyAddress", Common.CompanyInfo.Address);
            report.SetParameterValue("CompanyPhone", Common.CompanyInfo.Telephone);
            report.SetParameterValue("CompanyFax", Common.CompanyInfo.FaxNumber);
            return report;
        }

        public void PrintReport()
        {
           
                try
                {
                    crScaleTicket report = BuildReport();

                    Margins margins = new Margins();
                    report.PrintOptions.ApplyPageMargins(new PageMargins(margins.Left, margins.Top, margins.Right, margins.Bottom));
                    report.PrintOptions.PaperOrientation = PaperOrientation.Portrait;
                    report.PrintOptions.PaperSize = PaperSize.PaperA4;

                    if (Common.CheckPrinter(Setting.ReceiptPrintName))
                        report.PrintOptions.PrinterName = Setting.ReceiptPrintName;

                    if (Setting.IsPreviewReceiptPrint)
                    {
                        FrmPrintPreview form = new FrmPrintPreview(report);
                        form.ShowDialog();
                    }
                    else
                    {
                        report.PrintToPrinter(1, false, 0, 0);
                    }
                    try
                    {
                        LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Click in phieu");
                    }
                    catch
                    {
                    }
                }
                catch (CrystalReportsException ex)
                {
                    Library.Tools.MsgBox.Show("Lỗi hiển thị trang in. Error details: " + ex.Message, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
          
        }

        #region Click add vehicle button
        private void ClickAddVehicle()
        {
            try
            {
                // Only 15 vehicles per ticket.
                if (gridEX1.RowCount < 15)
                {
                    if (string.IsNullOrEmpty(this.ctrlVehicleID1.Text))
                    {
                        Library.Tools.MsgBox.Show("Bạn chưa nhập số xe!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    VehicleScaleDetail = new VehicleScaleDetailModel()
                    {
                        VehicleScaleID = _vehicleScale.VehicleScaleID,
                        VehicleScaleDetailID = Guid.NewGuid(),
                        Order = VehicleScale.VehicleScaleDetails.Count,
                        VehicleID = this.ctrlVehicleID1.Text,
                        IsSelected = true
                    };

                    VehicleScale.VehicleScaleDetails.Add(VehicleScaleDetail);

                    this.ctrlVehicleID1.Enabled = true;
                    //this.btnAddVehicle.Enabled = false;

                    this.gridEX1.Refetch();

                    var item = (from i in gridEX1.GetRows()
                                where (i.DataRow as VehicleScaleDetailModel).IsSelected
                                select i).SingleOrDefault();
                    this.gridEX1.Row = item.Position;
                    (item.DataRow as VehicleScaleDetailModel).IsSelected = false;
                    try
                    {
                        LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Click Them xe");
                    }
                    catch
                    {
                    }
                    this.numFirstWeight.Focus();
                }
            }
            catch (Exception ex)
            {
                Library.Tools.MsgBox.Show("Thêm xe xảy ra lỗi! Chi tiết lỗi: " + Environment.NewLine + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region Click reset first weight
        private void ClickResetFirstWeight()
        {
            this.VehicleScaleDetail.FirstWeight = 0M;
            this.numFirstWeight.Value = 0;
            this.numFirstWeight.Enabled = true;
            this.btnFirstWeight.Enabled = true;
            
            ClickResetSecondWeight();
            this.numFirstWeight.Focus();
        }
        #endregion

        #region Click reset second weight
        private void ClickResetSecondWeight()
        {
            this.VehicleScaleDetail.SecondWeight = 0M;
            this.numSecondWeight.Value = 0;
            this.numSecondWeight.Enabled = true;
            this.btnSecondWeight.Enabled = true;

            // Refresh data
            this.gridEX1.Refresh();
            this.numSecondWeight.Focus();
        }
        #endregion

        #region Close Form
        protected override void OnClosed(EventArgs e)
        {
            FrmMDI.Instance.btnBarCustomerList.Groups[0].Items.Remove(_buttonBarItem);
            ThisKey = null;
            base.OnClosed(e);
        }
        #endregion

        #endregion

        private bool NewTicket(out string detailerror)
        {
            detailerror = String.Empty;
            bool result = false;

            try
            {
                VehicleScaleDetail.EditedFirstWeight = VehicleScaleDetail.FirstWeight;
                VehicleScaleDetail.SecondWeight = VehicleScaleDetail.SecondWeight;
                _vehicleScale.CustomerID = this.cboCustomerID.Value.ToString();
                _vehicleScale.ProductID = this.cboProductID.Value.ToString();
                _vehicleScale.EmployeeID = Common.UserLogin.EmployeeID;
                _vehicleScale.ScaleDate = DateTime.Today;
                _vehicleScale.ModifiedByID = Common.UserLogin.EmployeeID;
                _vehicleScale.ModifiedDate = DateTime.Now;
                _vehicleScale.TotalFirstWeight = (decimal)this.gridEX1.GetTotalRow().Cells["FirstWeight"].Value;
                _vehicleScale.TotalSecondWeight = (decimal)this.gridEX1.GetTotalRow().Cells["SecondWeight"].Value;

                _vehicleScale.CreatedByID = Common.UserLogin.EmployeeID;
                _vehicleScale.CreationDate = DateTime.Now;
                result = _dataAccess.Add(_vehicleScale, out detailerror);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return result;
        }

        private bool SaveVehicleItem(out string detailerror)
        {
            detailerror = String.Empty;
            bool result = false;
            if (_isSelectedGrid && _firstweight != VehicleScaleDetail.FirstWeight)
            {
                VehicleScaleDetail.EditedFirstWeight = _firstweight;
                VehicleScaleDetail.NumberEdited = VehicleScaleDetail.NumberEdited + 1;
                VehicleScaleDetail.CreatedDate = DateTime.Now;
            }
            else
            {
                VehicleScaleDetail.EditedFirstWeight = VehicleScaleDetail.FirstWeight;
                VehicleScaleDetail.CreatedDate = DateTime.Now;
              
            }
            if (_isSelectedGrid && _secondweight != VehicleScaleDetail.SecondWeight)
            {
                VehicleScaleDetail.EditedSecondWeight = _secondweight;
                VehicleScaleDetail.NumberEdited = VehicleScaleDetail.NumberEdited + 1;
                VehicleScaleDetail.CreatedDate = DateTime.Now;

            }
            else
            {
                VehicleScaleDetail.SecondWeight = VehicleScaleDetail.SecondWeight;
                VehicleScaleDetail.CreatedDate = DateTime.Now;
            }
            try
            {
                _vehicleScale.CustomerID = this.cboCustomerID.Value.ToString();
                _vehicleScale.ProductID = this.cboProductID.Value.ToString();
                _vehicleScale.EmployeeID = Common.UserLogin.EmployeeID;
                _vehicleScale.ScaleDate = DateTime.Today;
                _vehicleScale.ModifiedByID = Common.UserLogin.EmployeeID;
                _vehicleScale.ModifiedDate = DateTime.Now;
                _vehicleScale.TotalFirstWeight = (decimal)this.gridEX1.GetTotalRow().Cells["FirstWeight"].Value;
                _vehicleScale.TotalSecondWeight = (decimal)this.gridEX1.GetTotalRow().Cells["SecondWeight"].Value;

                IVehicleScaleDetailDataAccess dataAccess = new VechileScaleDetailDataAccess();
                result = _dataAccess.Edit(_vehicleScale);
                if (result)
                    result = dataAccess.Save(VehicleScaleDetail, _vehicleScale.VehicleScaleID, out detailerror);

                _isSelectedGrid = false;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return result;
        }

        private bool RemoveVehicleItem(out string detailerror)
        {
            detailerror = String.Empty;
            bool result = false;

            try
            {
                if (VehicleScale.VehicleScaleDetails.Count == 1)
                {
                    _dataAccess.Delete(_vehicleScale);
                }
                else
                {
                    _vehicleScale.CustomerID = this.cboCustomerID.Value.ToString();
                    _vehicleScale.ProductID = this.cboProductID.Value.ToString();
                    _vehicleScale.EmployeeID = Common.UserLogin.EmployeeID;
                    _vehicleScale.ScaleDate = DateTime.Today;
                    _vehicleScale.ModifiedByID = Common.UserLogin.EmployeeID;
                    _vehicleScale.ModifiedDate = DateTime.Now;
                    _vehicleScale.TotalFirstWeight = (decimal)this.gridEX1.GetTotalRow().Cells["FirstWeight"].Value;
                    _vehicleScale.TotalSecondWeight = (decimal)this.gridEX1.GetTotalRow().Cells["SecondWeight"].Value;

                    _vehicleScale.CreatedByID = Common.UserLogin.EmployeeID;
                    _vehicleScale.CreationDate = DateTime.Now;
                    IVehicleScaleDetailDataAccess dataAccess = new VechileScaleDetailDataAccess();
                    result = _dataAccess.Edit(_vehicleScale);
                    if (result)
                        result = dataAccess.Delete(VehicleScaleDetail);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return result;
        }

        
    }
}
